package com.huluobo.a2206douyindemo.shop;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.huluobo.a2206douyindemo.R;
import com.huluobo.a2206douyindemo.adapter.ShopAdapter;
import com.huluobo.a2206douyindemo.databinding.ActivityShopBinding;
import com.huluobo.base.bean.CommonBeanResult;
import com.huluobo.base.bean.GoodsBeanResult;
import com.huluobo.base.mvvm.BaseMVVMActivity;

public class ShopActivity extends BaseMVVMActivity<ActivityShopBinding, ShopViewModel> {

    private ShopAdapter shopAdapter;

    @Override
    protected void initData() {
        viewModel.getGoods(0, 1, 10);
        viewModel.getGoodsSuccess.observe(this, goodsBeanResult -> {
            if (goodsBeanResult.getCode() == 200) {
                shopAdapter.getData().clear();
                shopAdapter.getData().addAll(goodsBeanResult.getData());
                shopAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(goodsBeanResult.getMessage());
            }
        });

        viewModel.getGoodsFailed.observe(this, s -> {
            Log.i("TagA", "获取商品列表失败:" + s);
        });

        viewModel.addToCartSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
        });

        viewModel.addToCartFailed.observe(this, s -> {
            Log.i("TagA", "添加购物车失败::" + s);
        });
    }

    @Override
    protected void initView() {
        binding.shopRv.setLayoutManager(new GridLayoutManager(this, 2));
        shopAdapter = new ShopAdapter();
        binding.shopRv.setAdapter(shopAdapter);

        shopAdapter.addChildClickViewIds(R.id.item_shop_add_to_cart);
        shopAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.item_shop_add_to_cart) {
                viewModel.addToCart(shopAdapter.getData().get(position).getId(), 1);
            }
        });

        binding.shopFloatBtn.setOnClickListener(v -> {
            startActivity(new Intent(this, CartActivity.class));
        });
    }

    @Override
    protected Class<ShopViewModel> getViewModel() {
        return ShopViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shop;
    }
}